export const validateEmail = (email) => {
  return String(email)
    .toLowerCase()
    .match(
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
};

export const formatNumber = (number) => {
  return new Intl.NumberFormat("en-US", {
    style: "decimal",
    maximumFractionDigits: 4,
  }).format(number);
};

export const formatUSDT = (number) => {
  return new Intl.NumberFormat("en-US", {
    style: "decimal",
    minimumFractionDigits: 3,
    maximumFractionDigits: 3,
  }).format(number);
};
export const formatPrice = (price) => {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
  }).format(price);
};

export const formatPrice1 = (price) => {
  let formattedPrice = new Intl.NumberFormat("en-US", {
    style: "decimal",
  }).format(Math.abs(price));
  if (price >= 0) {
    return `$${formattedPrice}`; // 添加美元符号前缀
  } else {
    return `-$${formattedPrice}`; // 对于负数，添加负号和美元符号
  }
};

export const stringifyFormData = (data) => {
  const formData = new FormData();
  for (const key in data) {
    // eslint-disable-next-line no-prototype-builtins
    if (data.hasOwnProperty(key)) {
      if (data[key]) {
        if (data[key].constructor === Array) {
          if (data[key][0]) {
            if (data[key][0].constructor === Object) {
              formData.append(key, JSON.stringify(data[key]));
            } else {
              data[key].forEach((item, index) => {
                formData.append(key + `[${index}]`, item);
              });
            }
          } else {
            formData.append(key + "[]", "");
          }
        } else if (data[key].constructor === Object) {
          formData.append(key, JSON.stringify(data[key]));
        } else {
          formData.append(key, data[key]);
        }
      } else {
        if (data[key] === 0) {
          formData.append(key, 0);
        } else {
          formData.append(key, "");
        }
      }
    }
  }
  return formData;
};

// 图片file转Base64
export const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (event) {
      resolve(event.target.result);
    };
    reader.readAsDataURL(file);
  });
};
// 图片base64转file
export const Base64Tofile = (base64Data, filename) => {
  return new Promise((resolve, reject) => {
    const parts = base64Data.split(";base64,");
    const contentType = parts[0].split(":")[1];
    const raw = window.atob(parts[1]);
    const rawLength = raw.length;

    // 创建一个Uint8Array，并使用字符串的长度来创建它
    const uInt8Array = new Uint8Array(rawLength);

    // 遍历字符串，每一个字符转换成一个ASCII码
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }

    // 使用Blob对象创建File对象
    const blob = new Blob([uInt8Array], { type: contentType });
    resolve(new File([blob], filename, { type: contentType }));
  });
};

// 图片压缩
export const compressImage = async (
  src,
  outputFormat = "image/jpeg",
  quality = 0.5
) => {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.src = src;
    image.onload = () => {
      let width = image.width;
      let height = image.height;

      const canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, width, height);
      const newDataUrl = canvas.toDataURL(outputFormat, quality);
      resolve(newDataUrl);
    };
    image.onerror = reject;
  });
};

// 图片压缩
export const compressImageMax = async (
  src,
  outputFormat = "image/jpeg",
  quality = 0.7
) => {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.src = src;
    image.onload = () => {
      let width = image.width;
      let height = image.height;

      const canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, width, height);

      const newDataUrl = canvas.toDataURL(outputFormat, quality);
      resolve(newDataUrl);
    };
    image.onerror = reject;
  });
};
